<?php
declare(strict_types=1);

namespace app\middleware;

use app\traits\ResponseTrait;
use Firebase\JWT\{JWT, Key};
use think\facade\Config;
use think\Request;
use think\facade\Log;

abstract class BaseAuth
{
    use ResponseTrait;

    public function handle($request, \Closure $next)
    {
        Log::debug('BaseAuth handling request: ' . $request->pathinfo());
        // ... 其他代码
    }

    /**
     * 验证 JWT token
     * @return array [bool $valid, array|string $info]
     */
    protected function validateToken(Request $request): array
    {
        // 获取token
        $token = $request->header('Authorization');
        if (empty($token)) {
            return [false, '请先登录'];
        }

        try {
            // 移除可能存在的Bearer前缀
            $token = str_replace('Bearer ', '', $token);
            
            // 解析token
            $decoded = JWT::decode($token, new Key(Config::get('jwt.key'), 'HS256'));
            
            // 验证token类型
            if ($decoded->type !== $this->getGuard()) {
                return [false, '无效的token类型'];
            }

            // 验证token是否过期
            if ($decoded->exp < time()) {
                return [false, 'token已过期'];
            }

            // 返回解析后的用户信息
            return [true, [
                'id' => $decoded->id,
                'type' => $decoded->type,
                'exp' => $decoded->exp
            ]];

        } catch (\Throwable $e) {
            return [false, 'token解析失败'];
        }
    }

    /**
     * 生成 JWT token
     */
    protected function generateToken(int $id, string $type): string
    {
        $time = time();
        $expire = Config::get('jwt.expire', 7200);

        $payload = [
            'iat' => $time,                    // 签发时间
            'exp' => $time + $expire,          // 过期时间
            'id' => $id,                       // 用户ID
            'type' => $type,                   // 用户类型
            'jti' => uniqid('', true)         // JWT ID，用于标识该JWT
        ];

        return JWT::encode($payload, Config::get('jwt.key'), 'HS256');
    }

    /**
     * 刷新 JWT token
     */
    protected function refreshToken(array $tokenInfo): string
    {
        return $this->generateToken($tokenInfo['id'], $tokenInfo['type']);
    }

    /**
     * 获取守卫名称
     */
    abstract protected function getGuard(): string;
} 